package com.soso.base.google.cron.schedule;

import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.soso.base.util.log.Logger;

public class ScheduleRuleA extends AbstractScheduleRule {
	
	private static final String REGEX="^every (\\d+) (hours|mins|minutes) from (\\d+:\\d+) to (\\d+:\\d+)$";
	
	public static void main(String []args){
		ScheduleBean scheduleBean=new ScheduleBean();
		scheduleBean.setScheduleTime("every 2 hours from 12:00 to 18:00");
		ScheduleRuleA a=new ScheduleRuleA();
		a.execute(scheduleBean,null);
	}
	
	/**
	 * every 2 hours from 10:00 to 14:00
	 */
	@Override
	public boolean execute(ScheduleBean scheduleBean,ScheduleRuleChain chain) {
		Pattern p = Pattern.compile(REGEX, Pattern.DOTALL);
        Matcher m = p.matcher(scheduleBean.getScheduleTime());
        if(!m.find()){
        	return chain.execute(scheduleBean);
        }
        Logger.debug(REGEX);
        int every=Integer.parseInt(m.group(1));
        String unit=m.group(2);
        Date from=toDate(m.group(3)+":00");
        Date to=toDate(m.group(4)+":00");
        if (!from.before(to)) {
			return false;
		}
        if(!validateBetween(from, to)){
        	return false;
        }
        if(!validateInterval(scheduleBean.getLastTime(), getSecond(every, unit))){
        	return false;
        }
        //更新缓存
        Logger.debug("SUCCESS");
        scheduleBean.setLastTime(new Date());
        return true;
	}

}
